﻿package net.wangit.dev.wizard;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;


public class Table2Unit {

	private static final String SQL = "select * from COLUMN where t=? order by o";

	public Table2Unit() {
	}

	public static final List<String> create(DB db, String unitId,
			String tableName, int unitType, Map<String, String> filterFields)
			throws Exception {
		List<String> elements = new ArrayList<String>();
		MapList columns = db.query(Table2Unit.SQL, tableName, 2);
		Table table = new Table("dev", "ELEMENT");
		for (int i = 0; i < columns.size(); i++) {
			Row row = columns.getRow(i);
			String elementId = row.get("c");
			if (filterFields == null || !filterFields.containsKey(elementId)) {
				ColumnRow cRow = table.addInsertRow();
				cRow.set("eid", elementId);
				cRow.set("n", row.get("cl"));
				cRow.set("uid", unitId);
				cRow.set("c", 1);
				cRow.set("b", 1);
				if (3 != unitType)
					cRow.set("vr", row.get("nn"));
				int type = row.getInt("dt", 2);
				cRow.set("vv", getValidator(type));
				cRow.set("o", (i + 1) * 10);
				cRow.set("a", "0");
				cRow.set("au", 0);
				cRow.set("s", 1);
				elements.add(elementId);
			}
		}

		db.save(table);
		return elements;
	}

	private static final String getValidator(int type) {
		switch (type) {
		case 11: // '\013'
		case 12: // '\f'
		case 13: // '\r'
			return "1";

		case 21: // '\025'
		case 22: // '\026'
		case 23: // '\027'
			return "2";

		case 31: // '\037'
			return "3";

		case 32: // ' '
			return "4";

		case 33: // '!'
			return "5";
		}
		return null;
	}
}
